package com.android.examplelist;

import java.sql.SQLException;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

public class OrmliteActivity extends Activity {

	private DatabaseHelper databaseHelper = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		TextView tv = new TextView(this);
		doSampleDatabaseStuff("onCreate", tv);
		
		setContentView(tv);
		
	}
	
	private void doSampleDatabaseStuff(String action, TextView tv) {
		
		try {
			Dao<SimpleData, Integer> simpleDao = getHelper().getSimpleDataDao();
			
			List<SimpleData> list = simpleDao.queryForAll();
			
			StringBuilder sb = new StringBuilder();
			
			sb.append("got ").append(list.size()).append(" entries in ").append(action).append("\n");
			
			int simpleC = 0;
			for (SimpleData simple : list) {
				sb.append("------------------------------------------\n");
				sb.append("[").append(simpleC).append("] = ").append(simple).append("\n");
				simpleC++;
			}
			sb.append("------------------------------------------\n");
			
			for (SimpleData simple : list) {
				simpleDao.delete(simple);
				sb.append("deleted id ").append(simple.id).append("\n");
				simpleC++;
			}
			
			
			int createNum;
			do {
				createNum = new Random().nextInt(3) + 1;
			} while (createNum == list.size());
			for (int i = 0; i < createNum; i++) {
				// create a new simple object
				long millis = System.currentTimeMillis();
				SimpleData simple = new SimpleData(millis);
				// store it in the database
				simpleDao.create(simple);

				// output it
				sb.append("------------------------------------------\n");
				sb.append("created new entry #").append(i + 1).append(":\n");
				sb.append(simple).append("\n");
				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					// ignore
				}
			}
			
			tv.setText(sb.toString());
			
		} catch (SQLException e) {
			tv.setText("Database exeption: " + e);
			return;
		}
	}

	
	/**
	 * You'll need this in your class to get the helper from the manager once per class.
	 */
	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
		}
		return databaseHelper;
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		/*
		 * You'll need this in your class to release the helper when done.
		 */
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}
	
}
